package com.dgj.log.service.log.impl;

import org.bson.types.ObjectId;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import com.dgj.log.dao.ILogDao;
import com.dgj.log.entities.Log;
import com.dgj.log.service.log.ILogService;
import com.dgj.mongo.entity.Query;
import com.dgj.utils.common.DateUtils;
import com.dgj.utils.web.pager.Pager;

/**
 * @author 崔海军 create at 2015年7月10日 下午3:22:07
 */
@IocBean(name = "logServices")
public class LogServiceImpl implements ILogService {

	@Inject
	private ILogDao logDaos;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dgj.log.service.log.ILogService#listByPage(int, int)
	 */
	@Override
	public Pager<Log> listByPage(int page, int pageSize, String appName) {
		Pager<Log> pager = new Pager<Log>(pageSize, page);
		com.dgj.mongo.Pager mongoPager = new com.dgj.mongo.Pager(page, pageSize);
		pager.setEntities(logDaos.listAllByPage(mongoPager, Query.me().append("timestamp", -1), appName));
		pager.setCount(logDaos.count(appName));
		return pager;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dgj.log.service.log.ILogService#detail(int)
	 */
	@Override
	public Log detail(String id, String appName) {
		return logDaos.findOneByCnd(Query.me().append("_id", new ObjectId(id)), appName);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dgj.log.service.log.ILogService#search(int, int,
	 * com.dgj.log.entities.Log)
	 */
	@Override
	public Pager<Log> search(int page, int pageSize, Log log, int order) {
		Pager<Log> pager = new Pager<Log>(pageSize, page);
		com.dgj.mongo.Pager mongoPager = new com.dgj.mongo.Pager(page, pageSize);
		Query query = Query.me();
		if (Strings.isNotBlank(log.getLevel())) {
			query.append("level", log.getLevel());
		}
		if (Strings.isNotBlank(log.getMessage())) {
			query.genLikeCnd("message", log.getMessage());
		}
		if (log.getStartDate() != null) {
			query.genGTECnd("timestamp", log.getStartDate());
			pager.addParas("startDate", DateUtils.format("yyyy-MM-dd hh:mm:ss", log.getStartDate()));
		}
		if (log.getEndDate() != null) {
			query.genLTECnd("timestamp", log.getEndDate());
			pager.addParas("endDate", DateUtils.format("yyyy-MM-dd hh:mm:ss", log.getEndDate()));
		}
		pager.setEntities(logDaos.findByPage(query, mongoPager, Query.me().append("timestamp", order), log.getAppName()));
		pager.setCount(logDaos.countByCnd(query, log.getAppName()));
		return pager;
	}
}
